import time
import services
import os
import subprocess

def service(service_alias):
    try:
        service_instance = services.resolve_service(service_alias)
        return service_instance
    except Exception as e:
        #print e
        return None

def launch_service(service_alias, actual_service_name):
    subprocess.Popen(["python", actual_service_name])

    service_instance = service(service_alias)
    while service_instance is None:
        time.sleep(1)
        service_instance = service(service_alias)

    print "MESSAGE:: started {0} ...".format(service_alias)

def wait_till_rpc_server_has_started():
    service_instance = service("rpcservice")

    while service_instance is None:
        time.sleep(1)
        service_instance = service("rpcservice")


if __name__ == "__main__":
    rpc_server_pid = subprocess.Popen(["python", "rpc_service.py"]).pid

    wait_till_rpc_server_has_started()

    print "MESSAGE:: RPC server started...."
    
    #launch_service("datastoreservice", "sqlitedatastoreservice.py")
    #launch_service("crawlerservice", "filecrawlerservice.py")
    #launch_service("webui", os.path.join("plugins","webui.py"))
